//
//  YWTempMissionManager.m
//  maintain
//
//  Created by Kyo on 16/3/4.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWTempMissionManager.h"
#import "YWTempMissionDBManager.h"
#import "WMHttpTool.h"
#import "MJExtension.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWResourceManager.h"
#import "YWLoginTool.h"
#import "YWNotifyManager.h"
#import "YWPatrolPicture.h"
#import "YWHandler.h"

@interface YWTempMissionManager ()
//@property (nonatomic, strong) dispatch_queue_t serialQueue;
@end

@implementation YWTempMissionManager
YWSingletonM(Manager)

- (BOOL)updateTempMissionWithTempMissionArray:(NSArray*)tempMissions{
    return [[YWTempMissionDBManager shareManager] updateTempMissionWithTempMissionArray:tempMissions];
}

- (NSArray*)tempMissionOfTypeWithMeOrOthers:(YWTempMissionType)tempMissionType page:(NSInteger)page{
    return [[YWTempMissionDBManager shareManager] tempMissionOfTypeWithMeOrOthers:tempMissionType page:page];
}

-(YWTempMission *)tempMissionWithTempMissionId:(NSInteger)tempMissionId{
    return [[YWTempMissionDBManager shareManager] tempMissionWithTempMissionId:tempMissionId];
}

- (BOOL)existTempMissionWithTempMissionId:(NSInteger)tempMissionId{
    return [[YWTempMissionDBManager shareManager] existTempMissionWithTempMissionId:tempMissionId];
}

-(BOOL)deleteTempMissionWithTempMissionId:(NSInteger)tempMissionId{
    return [[YWTempMissionDBManager shareManager] deleteTempMissionWithTempMissionId:tempMissionId];
}

- (BOOL)deletePictureOfTempMissionWithTempMissionId:(NSInteger)tempMissionId{
    return [[YWTempMissionDBManager shareManager] deletePictureOfTempMissionWithTempMissionId:tempMissionId];
}

- (BOOL)setTempMissionIsRead:(YWTempMission *)tempMission{
    return [[YWTempMissionDBManager shareManager] setTempMissionIsRead:tempMission];
}

- (BOOL)setAllTempMissionIsRead{
    return [[YWTempMissionDBManager shareManager] setAllTempMissionIsRead];
}

-(NSInteger)tempMissionNoReadCount{
    return [[YWTempMissionDBManager shareManager] tempMissionNoReadCount];
}

- (void)requestTempMissionWithPage:(NSInteger)page pageSize:(NSInteger)pageSize withComplete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool getTempMissionUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* tempMissions = [YWTempMission mj_objectArrayWithKeyValuesArray:json];
        
        [[YWTempMissionManager shareManager] updateTempMissionWithTempMissionArray:tempMissions];
        
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)postTempMissionWithTitle:(NSString *)title contnet:(NSString *)content completionTime:(NSString*)completionTime executors:(NSArray *)executors pistures:(NSArray *)pictures WithComplete:(void (^)(BOOL))complete{
    if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        if (complete) {
            complete(NO);
        }
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[YWResourceManager shareManager]
         uploadPatrolPictureToAliyunOSS:pictures
         complete:^(BOOL isError, NSArray* uploadPictures) {
             [self pictureCompleteHandleWithTitle:title contnet:content completionTime:completionTime executors:executors pistures:uploadPictures error:isError WithComplete:^(BOOL success) {
                 if (complete) {
                     complete(success);
                 }
             }];
         }];
    });
}

- (void)pictureCompleteHandleWithTitle:(NSString *)title contnet:(NSString *)content completionTime:(NSString*)completionTime executors:(NSArray *)executors pistures:(NSArray *)pictures error:(BOOL)isError WithComplete:(void (^)(BOOL))complete{
    //[[YWDBTool shareDBTool] updatePatrolPictureWithArray:pictures];
    if (!isError) {
        NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
        [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
        if (headersDic == nil) {if (complete) {complete(NO);}return;}
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setValue:title?:@"" forKey:@"title"];
        [params setValue:content?:@"" forKey:@"content"];
        completionTime = [completionTime stringByAppendingString:@":00"];
        [params setValue:completionTime?:@"" forKey:@"completionTime"];
        [executors enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
            [params setObject:@(handler.uniqueId) forKey:[NSString stringWithFormat:@"executors[%lu].uniqueId", (unsigned long)idx]];
        }];
        [pictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull pic, NSUInteger idx, BOOL * _Nonnull stop) {
            [params setObject:pic.bigUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].url", (unsigned long)idx]];
            [params setObject:pic.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].thumbnailUrl", (unsigned long)idx]];
            [params setObject:pic.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].previewUrl", (unsigned long)idx]];
        }];
        YWLog(@"%@",params);
        [[WMHttpTool shareHttpTool] postWithUrl:[YWCommonTool getTempMissionUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
            YWTempMission* tempMission = [YWTempMission mj_objectWithKeyValues:json];
            if (tempMission) {
                tempMission.createTime = [[NSDate date] timeIntervalSince1970]*1000;
                tempMission.toUserIds = [YWCommonTool handlerIdsWithHandlerArray:executors];
                [[YWTempMissionManager shareManager] updateTempMissionWithTempMissionArray:@[tempMission]];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshPostYWTempMissionNotification object:nil];
            }
            if (complete) {
                complete(YES);
            }
        } failure:^(NSHTTPURLResponse* response, NSError* error) {
            if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
            }else{
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"sendFailed", nil)];
            }
            if (complete) {
                complete(NO);
            }
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        }];
    }else{
        if (complete) {
            complete(NO);
        }
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"sendFailed", nil)];
    }
}

- (void)modifyNoticeWithtempMission:(YWTempMission*)tempMission needUploadPic:(NSArray *)needUploadPic uploadedPic:(NSArray *)uploadedPic completionTime:(NSString*)completionTime WithComplete:(void(^)(BOOL success))complete
{
    if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        if (complete) {
            complete(NO);
        }
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[YWResourceManager shareManager]
         uploadPatrolPictureToAliyunOSS:needUploadPic
         complete:^(BOOL isError, NSArray* uploadPictures) {
             [self pictureCompleteHandleWithTempMission:tempMission needUploadPic:uploadPictures uploadedPic:uploadedPic completionTime:completionTime error:isError WithComplete:^(BOOL success) {
                 if (complete) {
                     complete(success);
                 }
             }];
         }];
    });
}

- (void)pictureCompleteHandleWithTempMission:(YWTempMission*)tempMission needUploadPic:(NSArray *)needUploadPic uploadedPic:(NSArray *)uploadedPic completionTime:(NSString*)completionTime error:(BOOL)isError WithComplete:(void (^)(BOOL))complete{
    if (!isError) {
        NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
        [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
        if (headersDic == nil) {if (complete) {complete(NO);}return;}
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setValue:@(tempMission.tempMissionId)?:@"" forKey:@"id"];
        [params setValue:tempMission.title?:@"" forKey:@"title"];
        [params setValue:tempMission.content?:@"" forKey:@"content"];
        completionTime = [completionTime stringByAppendingString:@":00"];
        [params setValue:completionTime?:@"" forKey:@"completionTime"];
//        [executors enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
//            [params setObject:@(handler.uniqueId) forKey:[NSString stringWithFormat:@"executors[%lu].uniqueId", (unsigned long)idx]];
//        }];
        NSMutableArray * totalPictures = [NSMutableArray array];
        [totalPictures addObjectsFromArray:needUploadPic];
        [totalPictures addObjectsFromArray:uploadedPic];
        [totalPictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull pic, NSUInteger idx, BOOL * _Nonnull stop) {
            [params setObject:pic.bigUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].url", (unsigned long)idx]];
            [params setObject:pic.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].thumbnailUrl", (unsigned long)idx]];
            [params setObject:pic.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"imagesList[%lu].previewUrl", (unsigned long)idx]];
        }];
        YWLog(@"%@",params);
        [[WMHttpTool shareHttpTool] putWithUrl:[YWCommonTool getTempMissionUrl] params:params success:^(NSHTTPURLResponse *response, id json) {
            // 更新数据库
            NSTimeInterval time = [YWCommonTool timeIntervalWithDatestring:completionTime dateFormatter:KTimeFormatFullDateAndTime]*1000;
            tempMission.completionTime = time;
            tempMission.imagesList = totalPictures;
            [[YWTempMissionManager shareManager] updateTempMissionWithTempMissionArray:@[tempMission]];
            if (totalPictures.count==0) {
                [[YWTempMissionManager shareManager] deletePictureOfTempMissionWithTempMissionId:tempMission.tempMissionId];
            }
            //成功刷新
            [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshModifyYWTempMissionNotification object:nil];
            if (complete) {
                complete(YES);
            }
        } failure:^(NSHTTPURLResponse *response, NSError *error) {
            if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
            }else{
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"sendFailed", nil)];
            }
            if (complete) {
                complete(NO);
            }
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        }];
    }else{
        if (complete) {
            complete(NO);
        }
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"sendFailed", nil)];
    }
}
- (void)requestDeleteTempMission:(NSInteger)tempMissionId complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSString *url = [NSString stringWithFormat:@"%@/%ld",[YWCommonTool getTempMissionUrl],(long)tempMissionId];
    [[WMHttpTool shareHttpTool] deleteWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        BOOL success = [[YWTempMissionManager shareManager] deleteTempMissionWithTempMissionId:tempMissionId];
        if (success) {
            [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshDeleteYWTempMissionNotification object:nil];
        }
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
@end
